import { login,logout } from '@/api/login'
import { adminIndexAuthList } from '@/api/common'
import { adminUsersRead } from '@/api/personCenter/personCenter'
import { addAuth,removeAuth } from '@/utils/auth'
import Lockr from 'lockr'

const user = {
	state: {
		userInfo: null, // 用户信息
		// 权限信息
		allAuth: null, // 总权限信息 默认空 调整动态路由
	},

	mutations: {
		SET_USERINFO: (state, userInfo) => {
			state.userInfo = userInfo
		},
		SET_ALLAUTH: (state, allAuth) => {
			state.allAuth = allAuth
		}
	},

	actions: {
		// 登录
		Login({
			commit
		}, userInfo) {
			const username = userInfo.username.trim()
			return new Promise((resolve, reject) => {
				login(username, userInfo.password).then(response => {
					const data = response.data
					Lockr.set('authKey', data.authKey)
					Lockr.set('sessionId', data.sessionId)
					Lockr.set('userInfoId', data.userInfo.id)
					Lockr.set('loginUserInfo', data.userInfo)
					Lockr.set('authList', data.authList.api)
					// 请求header注入请求信息
					addAuth(data.authKey, data.sessionId)
					// 系统信息
					commit('SET_SYSTEMINFO', data.systeminfo)
					Lockr.set('systeminfo', data.systeminfo)

					commit('SET_USERINFO', data.userInfo)
					// 权限
					commit('SET_ALLAUTH', data.authList.api)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取权限
		getAuth({
			commit
		}) {
			return new Promise((resolve, reject) => {
				adminIndexAuthList().then((response) => {
					const data = response.data
					Lockr.set('authList', data.api)
					commit('SET_ALLAUTH', data.api)
					resolve(response)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 获取用户信息
		GetUserInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				adminUsersRead().then(response => {
					commit('SET_USERINFO', response.data)
					resolve(response)
				}).catch(error => {
					reject(error)
				})
			})
		},

		// 登出
		LogOut({
			commit
		}) {
			return new Promise((resolve, reject) => {
				logout().then(() => {
					/** flush 清空localStorage .rm('authKey') 按照key清除 */
					removeAuth()
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		}
	}
}

export default user
